<?php

/**
 * 和业务相关的函数
 */

use App\Common\CacheKey;
use App\Models\Option;
use App\Services\Doll;
use App\Support\Time;
use Illuminate\Support\Facades\Cache;

/**
 * 获取 option 配置项
 *
 * @param string $name
 * @param null $default
 * @return mixed
 */
function get_option($name, $default = null)
{
    $all = load_all_options();
    
    if (isset($all[$name])) {
        $value = $all[$name];
    } elseif ($option = Option::findByName($name)) {
        $value = $option->value;
    } else {
        $value = $default;
    }
    
    return $value;
}

/**
 * 添加一个 option 配置项，如果 name 已经存在，则更新。
 *
 * @param string $name
 * @param mixed $value
 */
function add_option($name, $value)
{
    update_options([$name => $value]);
}

/**
 * 更新一个 option 配置项，如果 name 不存在，则创建。
 *
 * @param string $name
 * @param mixed $value
 */
function update_option($name, $value)
{
    update_options([$name => $value]);
}

/**
 * 更新多个 option 配置项，不存在的，则创建。
 *
 * @param array $values
 */
function update_options($values)
{
    $names = array_keys($values);
    $options = Option::whereIn('name', $names)->get()->keyBy('name');
    
    foreach ($values as $key => $value) {
        $option = $options->get($key);
        
        if (is_null($option)) {
            Option::create(['name' => $key, 'value' => $value]);
        } else {
            $option->update(['value' => $value]);
        }
    }
    
    Cache::forget(CacheKey::$options);
}

/**
 * 删除 option 配置项
 *
 * @param string $name
 * @return bool|null
 * @throws Exception
 */
function delete_option($name)
{
    $option = Option::findByName($name);
    if (is_null($option)) {
        return true;
    }
    
    if ($deleted = $option->delete()) {
        Cache::forget(CacheKey::$options);
    }
    
    return $deleted;
}

/**
 * 加载所有 options
 *
 * @return array
 */
function load_all_options()
{
    static $options;
    
    if (is_null($options)) {
        // 缓存1个月
        $options = Cache::remember(CacheKey::$options, Time::MINUTES_OF_MONTH, function () {
            return Option::get()->pluck('value', 'name')->all();
        });
    }
    
    return $options;
}

/**
 * 把游戏记录转为商品数据
 *
 * @param \Illuminate\Database\Eloquent\Collection $records
 * @return array
 */
function game_records_to_wares($records)
{
    $wares = [];

    foreach ($records as $record) {
        $wareId = $record->ware_id;

        if (! isset($wares[$wareId])) {
            $wares[$wareId] = [
                'ware_id' => $wareId,
                'ware_name' => $record->ware_name,
                'ware_image' => $record->ware_image,
                'num' => 1,
            ];
        } else {
            $wares[$wareId]['num']++;
        }
    }
    
    return array_values($wares);
}

/**
 * 向硬件系统服务创建订单
 *
 * @param \App\Models\User $user
 * @param \App\Models\Address $address
 * @param array $wares
 * @return array
 *
 * @throws Exception
 */
function doll_send_order($user, $address, $wares)
{
    $array = [];
    foreach ($wares as $ware) {
        $array[] = [
            'goods_id' => $ware['ware_id'],
            'num' => $ware['num'],
        ];
    }
    
    $goodsList = json_encode($array);
    
    $doll = app(Doll::class);
    return $doll->createOrder(
        $user->id, $user->nickname, $goodsList, $address->fullAddress(), $address->phone, $address->consignee
    );
}

/**
 * 娃娃机视频方案
 *
 * @param null|string $scheme
 * @return bool|string
 */
function doll_video_scheme($scheme = null)
{
    $videoScheme = config('services.doll.video_scheme');
    
    if (empty($scheme)) {
        return $videoScheme;
    }
    
    return $scheme == $videoScheme;
}
